<template>
  <div class="CleaningReportbox">
    <!-- 顶部表单 -->
    <div class="topbox">
      <el-form ref="form" label-position="left" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="光伏系统">
              <FilterSelect2
                v-model="companyId"
                :optionlist="xitonglist"
                @updateModelValue="changexitong"
                :valuekey="{ name: 'name', value: 'id' }"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="报告日期">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :default-time="['00:00:00', '23:59:59']"
                style="width: 100%"
                size="small"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="13" style="text-align: right">
            <el-form-item label="">
              <el-button size="small" @click="chongzhi">重 置</el-button>
              <el-button size="small" type="primary" @click="gettablelist"
                >查 询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 主体内容 -->
    <div class="bodybox">
      <div class="title">
        <div>清洗报告记录</div>
        <div>
          <el-button size="small" type="primary" @click="addNew"
            >+ 新增</el-button
          >
          <TopTile
            @command="command"
            @daochu="daochu"
            @shuaxin="shuaxin"
          ></TopTile>
        </div>
      </div>
      <div class="table-section">
        <el-table
          ref="tabledata"
          :data="tableData"
          :size="issize"
          border
          v-loading="loading"
          max-height="calc(100% - 1px)"
          style="width: 100%"
          :header-cell-style="{
            'text-align': 'center',
            background: '#f5f5f5'
          }"
        >
          <el-table-column
            type="index"
            label="序号"
            width="70"
            align="center"
          />
          <el-table-column prop="className" label="光伏电站" align="center" />
          <el-table-column prop="reportName" label="报告名称" align="center" />
          <el-table-column prop="fillDate" label="填报时间" align="center" />
          <el-table-column prop="reportDate" label="报告日期" align="center" />
          <el-table-column prop="cleanUser" label="清洗人" align="center" />
          <el-table-column label="操作" width="300" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleBrowse(scope.row)"
              >
                浏览
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleDownload(scope.row)"
              >
                下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-section">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="text-align: right; margin-top: 20px"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="90%"
      :before-close="handleDialogClose"
      class="cleaning-report-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content">
        <!-- 顶部信息 -->
        <div class="dialog-header">
          <div class="header-left">
            <el-form :model="dialogForm" label-width="100px" size="small">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="电站名称">
                    <FilterSelect2
                      v-model="dialogForm.classId"
                      :optionlist="xitonglist"
                      @updateModelValue="changeDialogStation"
                      :valuekey="{ name: 'name', value: 'id' }"
                      :disabled="isBrowse"
                      :readonly="isBrowse"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="清洗日期">
                    <el-date-picker
                      v-model="dialogForm.cleaningDate"
                      type="date"
                      placeholder="请输入"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      style="width: 100%"
                      :disabled="isBrowse"
                      :readonly="isBrowse"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="报告日期">
                    <el-date-picker
                      v-model="dialogForm.reportDate"
                      type="date"
                      placeholder="默认当天"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      style="width: 100%"
                      :disabled="isBrowse"
                      :readonly="isBrowse || isEdit"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="header-right">
            <!-- 新增/编辑模式显示保存按钮 -->
            <el-button
              v-if="!isBrowse"
              type="primary"
              size="small"
              @click="handleSave"
            >
              保存
            </el-button>
            <!-- 浏览模式显示生成和下载按钮 -->
            <el-button
              v-if="isBrowse"
              type="primary"
              size="small"
              @click="handleCreatePdf"
            >
              生成
            </el-button>
            <el-button
              v-if="isBrowse"
              type="primary"
              size="small"
              :disabled="!createPdfFlag"
              @click="handleDownloadPdf"
            >
              下载
            </el-button>
          </div>
        </div>

        <!-- 报告标题 -->
        <div class="report-section">
          <div class="report-title">
            <h2>{{ reportTitle }}</h2>
          </div>
        </div>

        <!-- 清洗人、天气、温度 -->
        <div class="info-section">
          <el-form :model="dialogForm" label-width="80px" size="small">
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="清洗人">
                  <el-input
                    v-model="dialogForm.cleanUser"
                    placeholder="请输入"
                    size="small"
                    :readonly="isBrowse"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="天气">
                  <el-input
                    v-model="dialogForm.weather"
                    placeholder="请输入"
                    size="small"
                    :readonly="isBrowse"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="温度">
                  <el-input
                    v-model="dialogForm.temperature"
                    placeholder="请输入"
                    size="small"
                    :readonly="isBrowse"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 清洗设备详情 -->
        <div class="cleaning-details">
          <div class="section-title">
            <el-button
              v-if="!isBrowse"
              size="small"
              type="primary"
              @click="addCleaningDetail"
              >+新增</el-button
            >
          </div>
          <div class="details-table">
            <el-table :data="dialogForm.cleanDetails" border size="small">
              <el-table-column label="电站名称" min-width="120">
                <template>
                  <span>{{ dialogForm.className }}</span>
                </template>
              </el-table-column>
              <el-table-column label="屋面名称" min-width="120">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.roofName"
                    placeholder="请输入"
                    size="small"
                    :readonly="isBrowse"
                  />
                </template>
              </el-table-column>
              <el-table-column label="开始时间" min-width="120">
                <template slot-scope="scope">
                  <el-time-picker
                    v-model="scope.row.startTime"
                    placeholder="选择时间"
                    format="HH:mm"
                    value-format="HH:mm"
                    style="width: 100%"
                    size="small"
                    :readonly="isBrowse"
                    @change="validateTime(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="结束时间" min-width="120">
                <template slot-scope="scope">
                  <el-time-picker
                    v-model="scope.row.endTime"
                    placeholder="选择时间"
                    format="HH:mm"
                    value-format="HH:mm"
                    style="width: 100%"
                    size="small"
                    :readonly="isBrowse"
                    @change="validateTime(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="组件数量(片)" min-width="120">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.componentNum"
                    placeholder="请输入"
                    size="small"
                    :readonly="isBrowse"
                    @input="validateNumber(scope.row, 'componentNum')"
                  />
                </template>
              </el-table-column>
              <el-table-column label="水表读数(始)" min-width="120">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.waterMeterStart"
                    placeholder="请输入"
                    size="small"
                    :readonly="isBrowse"
                    @input="validateNumber(scope.row, 'waterMeterStart')"
                  />
                </template>
              </el-table-column>
              <el-table-column label="水表读数(终)" min-width="120">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.waterMeterEnd"
                    placeholder="请输入"
                    size="small"
                    :readonly="isBrowse"
                    @input="validateNumber(scope.row, 'waterMeterEnd')"
                  />
                </template>
              </el-table-column>
              <el-table-column label="逆变器度数(始)" min-width="120">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.inverterStart"
                    placeholder="请输入"
                    size="small"
                    :readonly="isBrowse"
                    @input="validateNumber(scope.row, 'inverterStart')"
                  />
                </template>
              </el-table-column>
              <el-table-column label="逆变器度数(终)" min-width="120">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.inverterEnd"
                    placeholder="请输入"
                    size="small"
                    :readonly="isBrowse"
                    @input="validateNumber(scope.row, 'inverterEnd')"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="80">
                <template slot-scope="scope">
                  <el-button
                    v-if="!isBrowse"
                    type="text"
                    size="small"
                    @click="removeCleaningDetail(scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 事项列表 -->
        <div class="matters-section">
          <div class="section-title">清洗事项</div>
          <div class="matters-table">
            <!-- 表头 -->
            <div class="table-header">
              <div class="header-cell category-cell">事项</div>
              <div class="header-cell index-cell"></div>
              <div class="header-cell content-cell"></div>
              <div class="header-cell confirm-cell">确认</div>
              <div class="header-cell remark-cell">备注</div>
            </div>

            <!-- 表格内容 -->
            <div class="table-body">
              <div
                v-for="(item, index) in processedMattersList"
                :key="index"
                class="table-row"
              >
                <!-- 分类标题列 -->
                <div
                  class="table-cell category-cell"
                  :style="
                    item.categoryRowspan > 0
                      ? `grid-row: span ${item.categoryRowspan}`
                      : 'display: none'
                  "
                >
                  <span v-if="item.category">
                    {{ item.category }}
                  </span>
                </div>

                <!-- 序号列 -->
                <div class="table-cell index-cell">
                  <span>{{ item.index }}</span>
                </div>

                <!-- 事项内容列 -->
                <div class="table-cell content-cell">
                  <span>{{ item.content }}</span>
                </div>

                <!-- 确认列 -->
                <div class="table-cell confirm-cell">
                  <el-button
                    v-if="!item.isNotice"
                    :type="item.status === 1 ? 'success' : 'danger'"
                    size="mini"
                    :disabled="isBrowse"
                    @click="toggleMatterStatus(getOriginalIndex(index))"
                  >
                    {{ item.status === 1 ? '✓' : '✗' }}
                  </el-button>
                </div>

                <!-- 备注列 -->
                <div class="table-cell remark-cell">
                  <el-input
                    v-if="!item.isNotice"
                    v-model="mattersList[getOriginalIndex(index)].remark"
                    placeholder="请输入"
                    size="small"
                    :readonly="isBrowse"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 照片上传 -->
        <div class="photo-section">
          <div class="section-title">照片</div>
          <div class="photo-upload">
            <el-upload
              v-if="!isBrowse"
              class="upload-demo"
              action="#"
              :http-request="handlePhotoUpload"
              :show-file-list="false"
              :before-upload="beforePhotoUpload"
              accept="image/*"
              :limit="1"
            >
              <div class="upload-area">
                <div v-if="!dialogForm.pic" class="upload-placeholder">
                  <i class="el-icon-plus"></i>
                  <p>点击上传照片</p>
                  <p class="upload-tip">支持 JPG、PNG 格式，大小不超过 2MB</p>
                </div>
                <div v-else class="uploaded-content">
                  <img
                    :src="getImageSrc(dialogForm.pic)"
                    class="uploaded-image"
                  />
                  <div class="image-overlay">
                    <el-button
                      type="text"
                      size="small"
                      @click.stop="removePhoto"
                    >
                      <i class="el-icon-delete"></i> 删除
                    </el-button>
                  </div>
                </div>
              </div>
            </el-upload>
            <!-- 浏览模式下的图片显示 -->
            <div v-else class="upload-area">
              <div v-if="dialogForm.pic" class="uploaded-content">
                <img
                  :src="getImageSrc(dialogForm.pic)"
                  class="uploaded-image"
                  @error="handleImageError"
                  @load="handleImageLoad"
                />
              </div>
              <div v-else class="upload-placeholder">
                <i class="el-icon-picture"></i>
                <p>暂无照片</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 生成数据按钮 -->
        <div class="generate-section">
          <el-button
            v-if="!isBrowse"
            type="primary"
            size="small"
            @click="generateData"
            >生成数据</el-button
          >
        </div>

        <!-- 数据表格 -->
        <div class="data-tables">
          <div class="table-container">
            <el-table :data="beforeData" border size="small">
              <el-table-column
                prop="type"
                label="类型"
                align="center"
                width="120"
              />
              <el-table-column label="前7天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[0]) }}
                </template>
              </el-table-column>
              <el-table-column label="前6天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[1]) }}
                </template>
              </el-table-column>
              <el-table-column label="前5天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[2]) }}
                </template>
              </el-table-column>
              <el-table-column label="前4天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[3]) }}
                </template>
              </el-table-column>
              <el-table-column label="前3天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[4]) }}
                </template>
              </el-table-column>
              <el-table-column label="前2天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[5]) }}
                </template>
              </el-table-column>
              <el-table-column label="前1天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[6]) }}
                </template>
              </el-table-column>
              <el-table-column label="当天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[7]) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="table-container">
            <el-table :data="afterData" border size="small">
              <el-table-column
                prop="type"
                label="类型"
                align="center"
                width="120"
              />
              <el-table-column label="后7天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[0]) }}
                </template>
              </el-table-column>
              <el-table-column label="后6天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[1]) }}
                </template>
              </el-table-column>
              <el-table-column label="后5天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[2]) }}
                </template>
              </el-table-column>
              <el-table-column label="后4天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[3]) }}
                </template>
              </el-table-column>
              <el-table-column label="后3天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[4]) }}
                </template>
              </el-table-column>
              <el-table-column label="后2天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[5]) }}
                </template>
              </el-table-column>
              <el-table-column label="后1天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[6]) }}
                </template>
              </el-table-column>
              <el-table-column label="当天" align="center">
                <template slot-scope="scope">
                  {{ formatDataValue(scope.row.data[7]) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 图表 -->
        <div
          ref="chartSection"
          class="chart-section"
          v-if="
            generatedData ||
            (isBrowse && chartOptions && Object.keys(chartOptions).length > 0)
          "
        >
          <nt-echart :options="chartOptions" style="height: 400px" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TopTile from '@/components/TopTitle/index.vue'
import FilterSelect2 from '@/components/FilterSelect2/index.vue'
import ntEchart from '@/components/nt-echart.vue'
import { exportexcel } from '@/utils/excel'
import { getphotovollistapi } from '@/api/Photovoltaic/analysis/YoyAnalysis'
import axios from 'axios'
import download from 'downloadjs'
import domToImage from 'dom-to-image'
import {
  getCleaningReportPageApi,
  addCleaningReportApi,
  updateCleaningReportApi,
  deleteCleaningReportApi,
  getCleaningReportDetailApi,
  generateDataApi,
  createPdfApi
} from '@/api/Photovoltaic/analysis/Cleaning-report'
import dayjs from 'dayjs'

export default {
  name: 'CleaningReport',
  components: {
    TopTile,
    FilterSelect2,
    ntEchart
  },
  data() {
    return {
      loading: false,
      issize: 'medium',
      companyId: '',
      xitonglist: [],
      dateRange: [
        dayjs().startOf('year').format('YYYY-MM-DD'),
        dayjs().format('YYYY-MM-DD')
      ],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '新增清洗报告',
      isBrowse: false, // 是否为浏览模式
      dialogForm: {
        classId: '',
        className: '',
        cleaningDate: '',
        reportDate: dayjs().format('YYYY-MM-DD'),
        cleanUser: '',
        weather: '',
        temperature: '',
        cleanDetails: [],
        pic: ''
      },
      isEdit: false,
      editId: null,
      generatedData: false,
      chartOptions: {},
      createPdfFlag: false, // PDF生成标志
      mattersList: [
        // 天气要求
        {
          index: 1,
          content: '当天辐照度低于500w/㎡,风力小于四级,无大雾,无大雨',
          status: 0,
          remark: '',
          category: '天气要求'
        },
        // 准备工作
        {
          index: 2,
          content: '穿着工作服,防水鞋,防水手套',
          status: 0,
          remark: '',
          category: '准备工作'
        },
        {
          index: 3,
          content: '佩戴安全帽',
          status: 0,
          remark: '',
          category: '准备工作'
        },
        {
          index: 4,
          content: '工作工具入袋',
          status: 0,
          remark: '',
          category: '准备工作'
        },
        {
          index: 5,
          content: '关闭屋顶泄水阀门',
          status: 0,
          remark: '',
          category: '准备工作'
        },
        {
          index: 6,
          content: '记录水,电度数',
          status: 0,
          remark: '',
          category: '准备工作'
        },
        // 组件清洗前
        {
          index: 7,
          content: '打开清洗给水箱及电源',
          status: 0,
          remark: '',
          category: '组件清洗前'
        },
        {
          index: 8,
          content: '在设备吊装前放置施工牌',
          status: 0,
          remark: '',
          category: '组件清洗前'
        },
        {
          index: 9,
          content: '设备吊装,确定起吊点附近5米内无人,注意起吊安全',
          status: 0,
          remark: '',
          category: '组件清洗前'
        },
        {
          index: 10,
          content: '检查屋面谁管是否有漏水破裂',
          status: 0,
          remark: '',
          category: '组件清洗前'
        },
        // 组件清洗中
        {
          index: 11,
          content: '使用与组件温差不大的清水清洗组件',
          status: 0,
          remark: '',
          category: '组件清洗中'
        },
        {
          index: 12,
          content:
            '使用水压小于4公斤的喷头,且其出水角度与光伏组件表面角度小于45度',
          status: 0,
          remark: '',
          category: '组件清洗中'
        },
        {
          index: 13,
          content:
            '使用柔软洁净的布料或平板拖把擦拭光伏组件,严禁硬物擦拭光伏组件',
          status: 0,
          remark: '',
          category: '组件清洗中'
        },
        {
          index: 14,
          content: '可使用清洁剂或者浓度75度的酒精,严禁使用腐蚀性溶剂',
          status: 0,
          remark: '',
          category: '组件清洗中'
        },
        {
          index: 15,
          content: '组件下沿无积灰带',
          status: 0,
          remark: '',
          category: '组件清洗中'
        },
        {
          index: 16,
          content: '组件表面无明显浮灰,无污斑',
          status: 0,
          remark: '',
          category: '组件清洗中'
        },
        {
          index: 17,
          content: '组件表面无损坏',
          status: 0,
          remark: '',
          category: '组件清洗中'
        },
        // 组件清洗后
        {
          index: 18,
          content: '关闭清洗给水箱及电源',
          status: 0,
          remark: '',
          category: '组件清洗后'
        },
        {
          index: 19,
          content: '打开屋顶泄水阀门',
          status: 0,
          remark: '',
          category: '组件清洗后'
        },
        {
          index: 20,
          content: '设备吊放,确定起吊点附近5米内无人,注意起吊安全',
          status: 0,
          remark: '',
          category: '组件清洗后'
        },
        {
          index: 21,
          content: '记录用水,电度数',
          status: 0,
          remark: '',
          category: '组件清洗后'
        },
        {
          index: 22,
          content: '记录清洗数量,人数,填写表格',
          status: 0,
          remark: '',
          category: '组件清洗后'
        },
        {
          index: 23,
          content: '清洗装备存放到指定地点',
          status: 0,
          remark: '',
          category: '组件清洗后'
        },
        {
          index: 24,
          content: '收回工作牌',
          status: 0,
          remark: '',
          category: '组件清洗后'
        },
        // 注意事项
        {
          index: 25,
          content: '在彩钢瓦屋顶行走时,严禁踩踏采光带,屋脊等屋面薄弱地方',
          status: 0,
          remark: '',
          category: '注意事项'
        },
        {
          index: 26,
          content: '严禁踩踏组件等电站资产',
          status: 0,
          remark: '',
          category: '注意事项'
        },
        {
          index: 27,
          content: '严禁非电站运维人员触碰及操作电站设备(清洗组件除外)',
          status: 0,
          remark: '',
          category: '注意事项'
        },
        {
          index: 28,
          content: '严禁在厂区内吸烟(吸烟区除外)',
          status: 0,
          remark: '',
          category: '注意事项'
        },
        {
          index: 29,
          content: '遵守屋顶业主及运维方有关管理制度',
          status: 0,
          remark: '',
          category: '注意事项'
        }
      ],
      beforeData: [
        { type: '发电量(kWh)', data: ['', '', '', '', '', '', '', ''] },
        { type: '电站效率(%)', data: ['', '', '', '', '', '', '', ''] }
      ],
      afterData: [
        { type: '发电量(kWh)', data: ['', '', '', '', '', '', '', ''] },
        { type: '电站效率(%)', data: ['', '', '', '', '', '', '', ''] }
      ]
    }
  },

  computed: {
    reportTitle() {
      if (this.dialogForm.cleaningDate && this.dialogForm.className) {
        return `${dayjs(this.dialogForm.cleaningDate).format(
          'YYYY年MM月DD日'
        )}${this.dialogForm.className}清洗报告`
      }
      return '清洗报告'
    },

    // 处理清洗事项表格数据，按分类分组
    processedMattersList() {
      const result = []
      let currentIndex = 1

      // 按分类分组
      const groupedMatters = {}
      this.mattersList.forEach((item) => {
        if (!groupedMatters[item.category]) {
          groupedMatters[item.category] = []
        }
        groupedMatters[item.category].push(item)
      })

      // 遍历每个分类
      Object.keys(groupedMatters).forEach((category) => {
        const items = groupedMatters[category]

        // 为每个分类创建一行，包含分类标题和第一个事项
        const firstItem = items[0]
        result.push({
          category: category,
          index: currentIndex,
          content: firstItem.content,
          status: firstItem.status,
          isCategory: false,
          rowspan: items.length, // 记录需要合并的行数
          categoryRowspan: items.length, // 分类标题需要合并的行数
          isNotice: category === '注意事项' // 标记是否为注意事项
        })
        currentIndex++

        // 添加剩余的事项（如果有的话）
        for (let i = 1; i < items.length; i++) {
          const item = items[i]
          result.push({
            category: '',
            index: currentIndex,
            content: item.content,
            status: item.status,
            isCategory: false,
            rowspan: 1,
            categoryRowspan: 0, // 不显示分类标题
            isNotice: category === '注意事项' // 标记是否为注意事项
          })
          currentIndex++
        }
      })

      return result
    }
  },

  async mounted() {
    const {
      data: { list }
    } = await getphotovollistapi()
    this.xitonglist = list
    const PhotoCompanyId = localStorage.getItem('PhotoCompanyId')
    this.$set(this, 'companyId', PhotoCompanyId ? +PhotoCompanyId : list[0].id)
    this.gettablelist()
  },

  methods: {
    // 系统下拉存本地
    changexitong(val) {
      localStorage.setItem('PhotoCompanyId', val)
    },

    // 重置
    chongzhi() {
      const PhotoCompanyId = localStorage.getItem('PhotoCompanyId')
      this.$set(
        this,
        'companyId',
        PhotoCompanyId ? +PhotoCompanyId : this.xitonglist[0].id
      )
      this.dateRange = [
        dayjs().startOf('year').format('YYYY-MM-DD'),
        dayjs().format('YYYY-MM-DD')
      ]
      this.currentPage = 1
      this.gettablelist()
    },

    // 获取表格数据
    async gettablelist() {
      this.loading = true
      try {
        const { data } = await getCleaningReportPageApi({
          classId: this.companyId,
          startDate: this.dateRange[0],
          endDate: this.dateRange[1],
          pageNo: this.currentPage - 1,
          pageSize: this.pageSize
        })
        this.tableData = data.list || []
        this.total = data.totalCount || 0
      } catch (error) {
        console.error('获取清洗报告数据失败:', error)
        this.tableData = []
      } finally {
        this.loading = false
      }
    },

    // 调节表格密度
    command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },

    // 导出
    daochu() {
      exportexcel(
        'pes-microservice-biz/pes/cleaning/report/export',
        {
          classId: this.companyId,
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        },
        '清洗报告记录'
      )
    },

    // 刷新列表
    shuaxin() {
      this.gettablelist()
      this.$message.success('列表刷新成功')
    },

    // 新增
    addNew() {
      this.isEdit = false
      this.editId = null
      this.isBrowse = false // 设置为新增模式
      this.dialogTitle = '新增清洗报告'
      this.dialogForm = {
        classId: this.companyId,
        className:
          this.xitonglist.find((item) => item.id === this.companyId)?.name ||
          '',
        cleaningDate: dayjs().format('YYYY-MM-DD'),
        reportDate: dayjs().format('YYYY-MM-DD'),
        cleanUser: '',
        weather: '',
        temperature: '',
        cleanDetails: [],
        pic: ''
      }

      // 重置清洗事项数据
      this.mattersList.forEach((item, index) => {
        this.mattersList[index].status = 0 // 默认未确认
        this.mattersList[index].remark = ''
      })

      // 重置数据表格
      this.beforeData = [
        { type: '发电量(kWh)', data: ['', '', '', '', '', '', '', ''] },
        { type: '电站效率(%)', data: ['', '', '', '', '', '', '', ''] }
      ]
      this.afterData = [
        { type: '发电量(kWh)', data: ['', '', '', '', '', '', '', ''] },
        { type: '电站效率(%)', data: ['', '', '', '', '', '', '', ''] }
      ]
      this.generatedData = false
      this.chartOptions = {}
      this.createPdfFlag = false
      this.dialogVisible = true
    },

    // 浏览
    async handleBrowse(row) {
      try {
        const { data } = await getCleaningReportDetailApi({ id: row.id })
        const entity = data.entity

        // 设置基本信息
        this.dialogForm = {
          ...entity,
          classId: entity.classId,
          className: entity.className,
          cleaningDate: entity.cleaningDate,
          reportDate: entity.reportDate,
          cleanUser: entity.cleanUser,
          weather: entity.weather,
          temperature: entity.temperature,
          cleanDetails: entity.cleanDetails || [],
          pic: entity.pic || ''
        }

        // 处理清洗事项数据
        if (entity.matters) {
          this.mattersList.forEach((item, index) => {
            const statusKey = `status${item.index}`
            const remarkKey = `remark${item.index}`
            if (entity.matters[statusKey] !== undefined) {
              this.mattersList[index].status = entity.matters[statusKey]
            }
            if (entity.matters[remarkKey] !== undefined) {
              this.mattersList[index].remark = entity.matters[remarkKey]
            }
          })
        }

        // 处理前7天和后7天数据 - 在浏览模式下自动生成数据
        try {
          console.log('生成数据API参数:', {
            classId: entity.classId,
            cleaningDate: entity.cleaningDate
          })

          const { data: generateData } = await generateDataApi({
            classId: entity.classId,
            cleaningDate: entity.cleaningDate
          })

          // 调试信息
          console.log('生成数据API响应:', generateData)

          // 处理表格数据
          const detail = generateData.entity.dataDetail
          this.beforeData[0].data = [
            detail.seventhLast,
            detail.sixthLast,
            detail.fifthLast,
            detail.fourthLast,
            detail.thirdLast,
            detail.secondLast,
            detail.firstLast,
            detail.today
          ]
          this.beforeData[1].data = [
            detail.seventhLastEff,
            detail.sixthLastEff,
            detail.fifthLastEff,
            detail.fourthLastEff,
            detail.thirdLastEff,
            detail.secondLastEff,
            detail.firstLastEff,
            detail.todayEff
          ]
          this.afterData[0].data = [
            detail.seventhNext,
            detail.sixthNext,
            detail.fifthNext,
            detail.fourthNext,
            detail.thirdNext,
            detail.secondNext,
            detail.firstNext,
            detail.today
          ]
          this.afterData[1].data = [
            detail.seventhNextEff,
            detail.sixthNextEff,
            detail.fifthNextEff,
            detail.fourthNextEff,
            detail.thirdNextEff,
            detail.secondNextEff,
            detail.firstNextEff,
            detail.todayEff
          ]

          this.generatedData = true
          // 生成图表数据
          this.generateChartFromData()
        } catch (error) {
          console.error('生成数据失败:', error)
          // 如果生成数据失败，使用默认的空数据
          this.generatedData = false
          this.$message.warning('生成数据失败，将显示空数据')
        }

        // 检查是否已经生成过PDF
        this.createPdfFlag =
          entity.createPdfFlag === '1' || entity.createPdfFlag === 1

        this.dialogTitle = '查看清洗报告'
        this.isBrowse = true // 设置为浏览模式
        this.dialogVisible = true
      } catch (error) {
        console.error('获取报告详情失败:', error)
        this.$message.error('获取报告详情失败')
      }
    },

    // 编辑
    async handleEdit(row) {
      try {
        const { data } = await getCleaningReportDetailApi({ id: row.id })
        const entity = data.entity

        // 设置基本信息
        this.dialogForm = {
          ...entity,
          classId: entity.classId,
          className: entity.className,
          cleaningDate: entity.cleaningDate,
          reportDate: entity.reportDate,
          cleanUser: entity.cleanUser,
          weather: entity.weather,
          temperature: entity.temperature,
          cleanDetails: entity.cleanDetails || [],
          pic: entity.pic || ''
        }

        // 处理清洗事项数据
        if (entity.matters) {
          this.mattersList.forEach((item, index) => {
            const statusKey = `status${item.index}`
            const remarkKey = `remark${item.index}`
            if (entity.matters[statusKey] !== undefined) {
              this.mattersList[index].status = entity.matters[statusKey]
            }
            if (entity.matters[remarkKey] !== undefined) {
              this.mattersList[index].remark = entity.matters[remarkKey]
            }
          })
        }

        // 处理前7天和后7天数据 - 在编辑模式下也生成数据
        try {
          console.log('编辑模式 - 生成数据API参数:', {
            classId: entity.classId,
            cleaningDate: entity.cleaningDate
          })

          const { data: generateData } = await generateDataApi({
            classId: entity.classId,
            cleaningDate: entity.cleaningDate
          })

          // 调试信息
          console.log('编辑模式 - 生成数据API响应:', generateData)

          // 处理表格数据
          const detail = generateData.entity.dataDetail
          this.beforeData[0].data = [
            detail.seventhLast,
            detail.sixthLast,
            detail.fifthLast,
            detail.fourthLast,
            detail.thirdLast,
            detail.secondLast,
            detail.firstLast,
            detail.today
          ]
          this.beforeData[1].data = [
            detail.seventhLastEff,
            detail.sixthLastEff,
            detail.fifthLastEff,
            detail.fourthLastEff,
            detail.thirdLastEff,
            detail.secondLastEff,
            detail.firstLastEff,
            detail.todayEff
          ]
          this.afterData[0].data = [
            detail.seventhNext,
            detail.sixthNext,
            detail.fifthNext,
            detail.fourthNext,
            detail.thirdNext,
            detail.secondNext,
            detail.firstNext,
            detail.today
          ]
          this.afterData[1].data = [
            detail.seventhNextEff,
            detail.sixthNextEff,
            detail.fifthNextEff,
            detail.fourthNextEff,
            detail.thirdNextEff,
            detail.secondNextEff,
            detail.firstNextEff,
            detail.todayEff
          ]

          this.generatedData = true
          // 生成图表数据
          this.generateChartFromData()
        } catch (error) {
          console.error('生成数据失败:', error)
          // 如果生成数据失败，使用默认的空数据
          this.generatedData = false
        }

        this.isEdit = true
        this.editId = row.id
        this.isBrowse = false // 设置为编辑模式
        this.createPdfFlag = false // 编辑模式下重置PDF生成标志
        this.dialogTitle = '编辑清洗报告'
        this.dialogVisible = true
      } catch (error) {
        console.error('获取报告详情失败:', error)
        this.$message.error('获取报告详情失败')
      }
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await deleteCleaningReportApi({ id: row.id })
            this.$message.success('删除成功')
            this.gettablelist()
          } catch (error) {
            this.$message.error('删除失败')
          }
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },

    // 下载
    handleDownload(row) {
      axios({
        method: 'POST',
        url: `/biz/pes-microservice-biz/pes/cleaning/report/download/pdf?id=${row.id}`,
        responseType: 'blob'
      }).then((res) => {
        const blob = new Blob([res.data], { type: 'application/pdf' })
        download(blob, `清洗报告.pdf`)
      })
    },

    // 新增清洗详情
    addCleaningDetail() {
      this.dialogForm.cleanDetails.push({
        componentNum: '',
        waterMeterStart: '',
        waterMeterEnd: '',
        inverterStart: '',
        inverterEnd: '',
        roofName: '',
        startTime: '',
        endTime: ''
      })
    },

    // 对话框内电站选择变化
    changeDialogStation(val) {
      const selectedStation = this.xitonglist.find((item) => item.id === val)
      this.dialogForm.className = selectedStation ? selectedStation.name : ''
    },

    // 删除清洗详情
    removeCleaningDetail(index) {
      this.dialogForm.cleanDetails.splice(index, 1)
    },

    // 获取原始索引
    getOriginalIndex(processedIndex) {
      // 根据processedIndex找到对应的原始索引
      const processedItem = this.processedMattersList[processedIndex]
      if (processedItem && processedItem.index) {
        // 在mattersList中找到对应的原始项目
        return this.mattersList.findIndex(
          (item) => item.index === processedItem.index
        )
      }
      return -1
    },

    // 切换事项状态
    toggleMatterStatus(index) {
      this.mattersList[index].status =
        this.mattersList[index].status === 1 ? 0 : 1
    },

    // 照片上传前验证
    beforePhotoUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    },

    // 处理照片上传
    handlePhotoUpload(options) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.dialogForm.pic = e.target.result
      }
      reader.readAsDataURL(options.file)
    },

    // 删除照片
    removePhoto() {
      this.dialogForm.pic = ''
    },

    // 验证数字输入
    validateNumber(row, field) {
      let value = row[field]
      if (value === '' || value === null || value === undefined) {
        return
      }

      // 只允许数字和小数点
      value = value.toString().replace(/[^\d.]/g, '')

      // 确保只有一个小数点
      const parts = value.split('.')
      if (parts.length > 2) {
        value = parts[0] + '.' + parts.slice(1).join('')
      }

      // 限制小数位数最多2位
      if (parts.length === 2 && parts[1].length > 2) {
        value = parts[0] + '.' + parts[1].substring(0, 2)
      }

      // 处理整数部分，不允许以0开头的多位数
      if (parts.length > 0) {
        const integerPart = parts[0]
        if (integerPart.length > 1 && integerPart.startsWith('0')) {
          // 如果是以0开头的多位数，只保留第一个非0数字
          const firstNonZeroIndex = integerPart.search(/[1-9]/)
          if (firstNonZeroIndex !== -1) {
            parts[0] = integerPart.substring(firstNonZeroIndex)
          } else {
            // 如果全是0，只保留一个0
            parts[0] = '0'
          }
          value = parts.join('.')
        }
      }

      // 更新值
      this.$set(row, field, value)
    },

    // 验证时间
    validateTime(row) {
      if (row.startTime && row.endTime) {
        const startTime = this.parseTime(row.startTime)
        const endTime = this.parseTime(row.endTime)

        if (endTime <= startTime) {
          this.$message.warning('结束时间不能早于或等于开始时间')
          row.endTime = ''
        }
      }
    },

    // 解析时间字符串为分钟数
    parseTime(timeStr) {
      const [hours, minutes] = timeStr.split(':').map(Number)
      return hours * 60 + minutes
    },

    // 格式化数据值，0或0.0显示为0
    formatDataValue(value) {
      if (value === null || value === undefined || value === '') {
        return ''
      }
      // 如果是0或0.0，显示为0
      if (value === 0 || value === '0' || value === 0.0 || value === '0.0') {
        return '0'
      }
      return value
    },

    // 生成数据
    async generateData() {
      try {
        const { data } = await generateDataApi({
          classId: this.dialogForm.classId,
          cleaningDate: this.dialogForm.cleaningDate
        })

        // 处理表格数据
        const detail = data.entity.dataDetail
        this.beforeData[0].data = [
          detail.seventhLast,
          detail.sixthLast,
          detail.fifthLast,
          detail.fourthLast,
          detail.thirdLast,
          detail.secondLast,
          detail.firstLast,
          detail.today
        ]
        this.beforeData[1].data = [
          detail.seventhLastEff,
          detail.sixthLastEff,
          detail.fifthLastEff,
          detail.fourthLastEff,
          detail.thirdLastEff,
          detail.secondLastEff,
          detail.firstLastEff,
          detail.todayEff
        ]
        this.afterData[0].data = [
          detail.seventhNext,
          detail.sixthNext,
          detail.fifthNext,
          detail.fourthNext,
          detail.thirdNext,
          detail.secondNext,
          detail.firstNext,
          detail.today
        ]
        this.afterData[1].data = [
          detail.seventhNextEff,
          detail.sixthNextEff,
          detail.fifthNextEff,
          detail.fourthNextEff,
          detail.thirdNextEff,
          detail.secondNextEff,
          detail.firstNextEff,
          detail.todayEff
        ]

        // 处理图表数据
        this.chartOptions = {
          title: {
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['发电量', '效率'],
            top: 30
          },
          xAxis: {
            type: 'category',
            data: [
              '前7天',
              '前6天',
              '前5天',
              '前4天',
              '前3天',
              '前2天',
              '前1天',
              '当天',
              '后1天',
              '后2天',
              '后3天',
              '后4天',
              '后5天',
              '后6天',
              '后7天'
            ]
          },
          yAxis: [
            {
              type: 'value',
              name: '发电量(kWh)',
              position: 'left'
            },
            {
              type: 'value',
              name: '效率(%)',
              position: 'right'
            }
          ],
          series: [
            {
              name: '发电量',
              type: 'bar',
              data: [...this.beforeData[0].data, ...this.afterData[0].data]
            },
            {
              name: '效率',
              type: 'line',
              yAxisIndex: 1,
              data: [...this.beforeData[1].data, ...this.afterData[1].data]
            }
          ]
        }

        this.generatedData = true
        this.$message.success('数据生成成功')
      } catch (error) {
        this.$message.error('生成数据失败')
      }
    },

    // 保存
    async handleSave() {
      try {
        // 检查是否已生成数据
        if (!this.generatedData) {
          this.$message.warning('请先点击"生成数据"按钮获取数据后再保存')
          return
        }

        const matters = {}
        // 直接遍历mattersList，过滤掉注意事项
        this.mattersList
          .filter((item) => item.category !== '注意事项') // 过滤掉注意事项
          .forEach((item) => {
            matters[`status${item.index}`] = item.status
            matters[`remark${item.index}`] = item.remark
          })

        // 处理清洗详情数据，移除stationName字段
        const cleanDetails = this.dialogForm.cleanDetails.map((detail) => {
          const { stationName, ...rest } = detail
          return rest
        })

        // 处理图片数据，去掉base64前缀
        const processedPic = this.dialogForm.pic
          ? this.dialogForm.pic.replace(/^data:image\/[^;]+;base64,/, '')
          : ''

        // 构建dataDetail数据
        const dataDetail = {
          classId: this.dialogForm.classId,
          seventhLast: this.beforeData[0].data[0] || 0,
          sixthLast: this.beforeData[0].data[1] || 0,
          fifthLast: this.beforeData[0].data[2] || 0,
          fourthLast: this.beforeData[0].data[3] || 0,
          thirdLast: this.beforeData[0].data[4] || 0,
          secondLast: this.beforeData[0].data[5] || 0,
          firstLast: this.beforeData[0].data[6] || 0,
          today: this.beforeData[0].data[7] || 0,
          seventhLastEff: this.beforeData[1].data[0] || 0,
          sixthLastEff: this.beforeData[1].data[1] || 0,
          fifthLastEff: this.beforeData[1].data[2] || 0,
          fourthLastEff: this.beforeData[1].data[3] || 0,
          thirdLastEff: this.beforeData[1].data[4] || 0,
          secondLastEff: this.beforeData[1].data[5] || 0,
          firstLastEff: this.beforeData[1].data[6] || 0,
          todayEff: this.beforeData[1].data[7] || 0,
          seventhNext: this.afterData[0].data[0] || 0,
          sixthNext: this.afterData[0].data[1] || 0,
          fifthNext: this.afterData[0].data[2] || 0,
          fourthNext: this.afterData[0].data[3] || 0,
          thirdNext: this.afterData[0].data[4] || 0,
          secondNext: this.afterData[0].data[5] || 0,
          firstNext: this.afterData[0].data[6] || 0,
          fifthNextEff: this.afterData[1].data[2] || 0,
          fourthNextEff: this.afterData[1].data[3] || 0,
          thirdNextEff: this.afterData[1].data[4] || 0,
          secondNextEff: this.afterData[1].data[5] || 0,
          firstNextEff: this.afterData[1].data[6] || 0,
          seventhNextEff: this.afterData[1].data[0] || 0,
          sixthNextEff: this.afterData[1].data[1] || 0
        }

        const data = {
          ...this.dialogForm,
          pic: processedPic,
          cleanDetails,
          matters,
          dataDetail
        }

        if (this.isEdit) {
          const response = await updateCleaningReportApi(data)
          if (response.code === '200' || response.code === 200) {
            this.$message.success('更新成功')
          } else {
            this.$message.error(response.message || '更新失败')
            return
          }
        } else {
          const response = await addCleaningReportApi(data)
          if (response.code === '200' || response.code === 200) {
            this.$message.success('新增成功')
          } else {
            this.$message.error(response.message || '新增失败')
            return
          }
        }

        this.dialogVisible = false
        this.isBrowse = false // 重置浏览状态
        this.generatedData = false
        this.chartOptions = {}
        this.gettablelist()
      } catch (error) {
        this.$message.error(this.isEdit ? '更新失败' : '新增失败')
      }
    },

    // 生成PDF
    async handleCreatePdf() {
      if (!this.generatedData) return this.$message.warning('数据加载未完成')

      try {
        // 获取图表数据
        const chartElement = this.$refs.chartSection
        let chartImage = ''

        if (chartElement) {
          const fullImageData = await domToImage.toPng(chartElement, {
            pixelRatio: 2,
            backgroundColor: '#fff'
          })
          // 去掉base64前缀，只保留数据部分（支持所有图片格式）
          chartImage = fullImageData.replace(/^data:image\/[^;]+;base64,/, '')
        }

        await createPdfApi({
          id: this.dialogForm.id,
          dataImage:
            chartImage ||
            (this.chartOptions ? JSON.stringify(this.chartOptions) : '')
        })

        this.$message.success('PDF生成成功，当前可下载报告')
        this.createPdfFlag = true
      } catch (error) {
        console.error('PDF生成失败:', error)
        this.$message.error('PDF生成失败')
      }
    },

    // 下载PDF
    handleDownloadPdf() {
      axios({
        method: 'POST',
        url: `/biz/pes-microservice-biz/pes/cleaning/report/download/pdf?id=${this.dialogForm.id}`,
        responseType: 'blob'
      }).then((res) => {
        const blob = new Blob([res.data], { type: 'application/pdf' })
        download(blob, `清洗报告.pdf`)
      })
    },

    // 从现有数据生成图表
    generateChartFromData() {
      if (this.beforeData.length > 0 && this.afterData.length > 0) {
        this.chartOptions = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['发电量', '效率'],
            top: 30
          },
          xAxis: {
            type: 'category',
            data: [
              '前7天',
              '前6天',
              '前5天',
              '前4天',
              '前3天',
              '前2天',
              '前1天',
              '当天',
              '后1天',
              '后2天',
              '后3天',
              '后4天',
              '后5天',
              '后6天',
              '后7天'
            ]
          },
          yAxis: [
            {
              type: 'value',
              name: '发电量(kWh)',
              position: 'left'
            },
            {
              type: 'value',
              name: '效率(%)',
              position: 'right'
            }
          ],
          series: [
            {
              name: '发电量',
              type: 'bar',
              data: [...this.beforeData[0].data, ...this.afterData[0].data]
            },
            {
              name: '效率',
              type: 'line',
              yAxisIndex: 1,
              data: [...this.beforeData[1].data, ...this.afterData[1].data]
            }
          ]
        }
      }
    },

    // 图片加载成功
    handleImageLoad() {
      console.log('图片加载成功')
    },

    // 获取图片源
    getImageSrc(picData) {
      if (!picData) return ''

      // 如果已经是完整的data URL，直接返回
      if (picData.startsWith('data:image/')) {
        return picData
      }

      // 如果是Base64数据，添加前缀
      if (picData.startsWith('iVBORw0KGgo') || picData.startsWith('/9j/')) {
        // 根据数据开头判断图片类型
        let mimeType = 'image/png'
        if (picData.startsWith('/9j/')) {
          mimeType = 'image/jpeg'
        }
        return `data:${mimeType};base64,${picData}`
      }

      return picData
    },

    // 图片加载失败
    handleImageError(event) {
      console.error('图片加载失败:', event)
      console.log('图片数据:', this.dialogForm.pic)
      this.$message.error('图片加载失败')
    },

    // 对话框关闭处理
    handleDialogClose() {
      this.dialogVisible = false
      this.isBrowse = false // 重置浏览状态
      this.generatedData = false
      this.chartOptions = {}
      this.createPdfFlag = false
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.gettablelist()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.gettablelist()
    }
  }
}
</script>

<style lang="scss" scoped>
.CleaningReportbox {
  height: 100%;
  padding: 10px;

  .topbox {
    height: 80px;
    background-color: #fff;
    padding: 20px;
    margin-bottom: 10px;
  }

  .bodybox {
    height: calc(100% - 90px);
    background-color: #fff;
    padding: 20px;

    .title {
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      > div:first-child {
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }

      > div:last-child {
        display: flex;
        gap: 10px;
        align-items: center;
      }
    }

    .table-section {
      height: calc(100% - 120px);
    }

    .pagination-section {
      margin-top: 20px;
    }
  }
}

.cleaning-report-dialog {
  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;

    .header-left {
      width: 50%;
    }

    .header-right {
      display: flex;
      gap: 10px;
    }
  }

  .report-section {
    margin-bottom: 20px;

    .report-title {
      text-align: center;
      margin-bottom: 20px;

      h2 {
        margin: 0;
        color: #333;
        font-size: 18px;
      }
    }
  }

  .info-section {
    width: 40%;
    margin-left: auto;
    margin-right: 0;
  }

  .section-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .cleaning-details {
    margin-bottom: 20px;

    .details-table {
      border: 1px solid #dcdfe6;
      border-radius: 4px;

      .el-table {
        .el-table__body-wrapper {
          overflow: visible;
        }
      }
    }
  }

  .matters-section {
    margin-bottom: 20px;

    .matters-table {
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      overflow: hidden;

      .table-header {
        display: flex;
        background-color: #f5f5f5;
        border-bottom: 1px solid #dcdfe6;

        .header-cell {
          padding: 12px 8px;
          font-weight: 600;
          text-align: center;
          border-right: 1px solid #dcdfe6;
          font-size: 14px;
          color: #333;

          &:last-child {
            border-right: none;
          }
        }

        .category-cell {
          width: 120px;
        }

        .index-cell {
          width: 60px;
        }

        .content-cell {
          flex: 1;
          min-width: 300px;
        }

        .confirm-cell {
          width: 100px;
        }

        .remark-cell {
          width: 200px;
        }
      }

      .table-body {
        display: grid;
        grid-template-columns: 120px 60px 1fr 100px 200px;
        grid-auto-rows: minmax(40px, auto);
        border-bottom: 1px solid #dcdfe6;

        .table-row {
          display: contents;

          .table-cell {
            padding: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-right: 1px solid #dcdfe6;
            border-bottom: 1px solid #dcdfe6;
            font-size: 13px;

            &:last-child {
              border-right: none;
            }

            &.category-cell {
              justify-content: center;
              border-right: 1px solid #dcdfe6;
            }

            &.index-cell {
              justify-content: center;
              font-weight: 500;
            }

            &.content-cell {
              justify-content: flex-start;
              text-align: left;
              min-width: 300px;
            }

            &.confirm-cell {
              justify-content: center;
            }

            &.remark-cell {
              padding: 4px 8px;

              .el-input {
                width: 100%;
              }
            }
          }
        }
      }
    }
  }

  .photo-section {
    margin-bottom: 20px;

    .photo-upload {
      .upload-area {
        width: 200px;
        height: 150px;
        border: 2px dashed #d9d9d9;
        border-radius: 6px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        transition: border-color 0.3s;
        position: relative;
        overflow: hidden;

        &:hover {
          border-color: #409eff;
        }

        .upload-placeholder {
          text-align: center;
          color: #8c939d;

          .el-icon-plus {
            font-size: 28px;
            margin-bottom: 8px;
          }

          p {
            margin: 4px 0;
            font-size: 14px;
          }

          .upload-tip {
            font-size: 12px;
            color: #c0c4cc;
          }
        }

        .uploaded-content {
          position: relative;
          width: 100%;
          height: 100%;

          .uploaded-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 4px;
          }

          .image-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: opacity 0.3s;

            &:hover {
              opacity: 1;
            }

            .el-button {
              color: #fff;
              border-color: #fff;

              &:hover {
                background: #fff;
                color: #409eff;
              }
            }
          }
        }
      }
    }
  }

  .generate-section {
    text-align: left;
    margin-bottom: 20px;
  }

  .data-tables {
    margin-bottom: 20px;

    .table-container {
      margin-bottom: 15px;

      h4 {
        margin: 0 0 10px 0;
        color: #333;
      }
    }
  }

  .chart-section {
    margin-bottom: 20px;
  }
}
</style>
